<!-- 能效基准 -->
<template>
  <div class="app-container">
    <div v-show="showTable">
      <div class="tabs">
        <px-form ref="queryRef" class="custom-form-ui-new" :model="queryParams" :inline="true" label-width="68px">
          <px-form-item label="名称" prop="name">
            <px-input v-model="queryParams.name" placeholder="请输入名称" clearable style="width: 240px" />
          </px-form-item>
          <px-form-item label="时间" style="width: 460px">
            <px-date-picker v-model="dateRange" type="monthrange" start-placeholder="开始月份" end-placeholder="结束月份" value-format="YYYY-MM" />
          </px-form-item>
          <px-form-item>
            <px-button type="primary" @click="getList">查询</px-button>
            <px-button @click="resetQuery">重置</px-button>
          </px-form-item>
        </px-form>
      </div>
      <div class="mb-4">
        <px-button v-has="'ALL_ENERGY_BENCHMARK_ADD'" type="primary" @click="handleFn(null, 'ADD')">新增</px-button>
        <px-button v-has="'ALL_ENERGY_BENCHMARK_HISTORY'" type="primary" @click="historyAnsys">历史数据分析</px-button>
      </div>
      <div v-loading="tableLoading" class="table-content">
        <px-table
          :data="tableData"
          border
          show-overflow-tooltip
          height="calc(100vh - 355px)"
          :header-cell-style="{ background: '#e7eefb', color: '#000' }"
        >
          <px-table-column label="序号" width="60" align="center" fixed="left">
            <template #default="{ $index }">
              {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
            </template>
          </px-table-column>
          <px-table-column prop="name" label="名称" align="center" />
          <px-table-column prop="time" label="开始时间-结束时间" align="center" min-width="300">
            <template #default="scope">
              <div>
                {{ scope.row.startTime ? scope.row.startTime.substring(0, 7) : "" }}-{{ scope.row.endTime ? scope.row.endTime.substring(0, 7) : "" }}
              </div>
            </template>
          </px-table-column>
          <px-table-column prop="standardValue" label="单位产品综合能耗基准(tce/pcs)" align="center" min-width="160" />
          <px-table-column label="操作" width="150" fixed="right" align="center">
            <template #default="scope">
              <px-tooltip content="查看" placement="top">
                <px-button v-has="'ALL_ENERGY_BENCHMARK_VIEW'" link icon="View" type="primary" @click="handleFn(scope.row, 'VIEW')" />
              </px-tooltip>
              <px-tooltip content="编辑" placement="top">
                <px-button v-has="'ALL_ENERGY_BENCHMARK_EDIT'" link icon="EditPen" type="primary" @click="handleFn(scope.row, 'EDIT')" />
              </px-tooltip>
              <px-tooltip content="删除" placement="top">
                <px-button v-has="'ALL_ENERGY_BENCHMARK_DEL'" link icon="Delete" type="danger" @click="handleDelete(scope.row)" />
              </px-tooltip>
            </template>
          </px-table-column>
          <template #empty>
            <px-empty :image-size="150" />
          </template>
        </px-table>
        <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
      </div>
    </div>
    <px-dialog v-model="dialogVisible" title="历史数据分析" width="50%" align-center>
      <px-form ref="queryLineRef" :model="queryLineParams">
        <px-form-item style="width: 460px">
          <px-date-picker
            v-model="dateLineRange"
            :clearable="false"
            type="monthrange"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
            value-format="YYYY-MM"
            @change="getLineData"
          />
        </px-form-item>
      </px-form>
      <div v-loading="chartLoading" class="chart_item">
        <lineCharts :key="midKey" :border="false" :border-ridus="false" :box-shadow="false" :options="linesOptions" :width="300" :height="420" />
      </div>
    </px-dialog>
    <div v-show="!showTable" v-loading="detailLoading" class="add-edit-content">
      <div class="add-btn">
        <px-button type="primary" :icon="ArrowLeft" @click="cancelFn">返回</px-button>
      </div>
      <div class="add-content">
        <px-form
          ref="detailRef"
          :rules="rules"
          :model="detailParams"
          :inline="true"
          class="base-info-form"
          label-width="150px"
          label-position="right"
        >
          <ReCollapse class="mb-4" title="基本信息">
            <div class="form-item-con">
              <!-- 名称、时间、电、自来水 -->
              <px-row>
                <px-col :span="6">
                  <px-form-item label="名称" prop="name">
                    <px-input v-model="detailParams.name" maxlength="50" :disabled="fromDisabled" placeholder="请输入名称" clearable />
                  </px-form-item>
                </px-col>
                <px-col :span="6">
                  <px-form-item label="开始时间-结束时间" prop="startTime">
                    <px-date-picker
                      v-model="dateDetailRange"
                      type="monthrange"
                      start-placeholder="开始月份"
                      end-placeholder="结束月份"
                      value-format="YYYY-MM"
                      :disabled="fromDisabled"
                      @change="changeTime"
                    />
                  </px-form-item>
                </px-col>
                <px-col :span="6">
                  <px-form-item label="单位产品电能耗" prop="electricity">
                    <px-input
                      v-model="detailParams.electricity"
                      type="text"
                      maxlength="6"
                      :formatter="value => value.replace(/[^\d.]/g, '')"
                      :disabled="fromDisabled"
                      placeholder="最大值是100000"
                      clearable
                      @input="val => validateInput(val, 'electricity')"
                      @blur="val => onInputBlur(val, 'electricity')"
                    >
                      <template #append>KWh/pcs</template>
                    </px-input>
                  </px-form-item>
                </px-col>
                <px-col :span="6">
                  <px-form-item label="单位产品自来水能耗" prop="water">
                    <px-input
                      v-model="detailParams.water"
                      type="text"
                      maxlength="6"
                      :formatter="value => value.replace(/[^\d.]/g, '')"
                      :disabled="fromDisabled"
                      placeholder="最大值是100000"
                      clearable
                      @input="val => validateInput(val, 'water')"
                      @blur="val => onInputBlur(val, 'water')"
                    >
                      <template #append>m3/pcs</template>
                    </px-input>
                  </px-form-item>
                </px-col>
              </px-row>
              <!-- 天然气、再生水、热水、大宗气-->
              <px-row>
                <px-col :span="6">
                  <px-form-item label="单位产品天然气能耗" prop="ng">
                    <px-input
                      v-model="detailParams.ng"
                      type="text"
                      maxlength="6"
                      :formatter="value => value.replace(/[^\d.]/g, '')"
                      :disabled="fromDisabled"
                      placeholder="最大值是100000"
                      clearable
                      @input="val => validateInput(val, 'ng')"
                      @blur="val => onInputBlur(val, 'ng')"
                    >
                      <template #append>Nm3/pcs</template>
                    </px-input>
                  </px-form-item>
                </px-col>
                <px-col :span="6">
                  <px-form-item label="单位产品再生水能耗" prop="reclaim">
                    <px-input
                      v-model="detailParams.reclaim"
                      type="text"
                      maxlength="6"
                      :formatter="value => value.replace(/[^\d.]/g, '')"
                      :disabled="fromDisabled"
                      placeholder="最大值是100000"
                      clearable
                      @input="val => validateInput(val, 'reclaim')"
                      @blur="val => onInputBlur(val, 'reclaim')"
                    >
                      <template #append>tce/pcs</template>
                    </px-input>
                  </px-form-item>
                </px-col>
                <px-col :span="6">
                  <px-form-item label="单位产品蒸汽/热水能耗" prop="hotSteam">
                    <px-input
                      v-model="detailParams.hotSteam"
                      type="text"
                      maxlength="6"
                      :formatter="value => value.replace(/[^\d.]/g, '')"
                      :disabled="fromDisabled"
                      placeholder="最大值是100000"
                      clearable
                      @input="val => validateInput(val, 'hotSteam')"
                      @blur="val => onInputBlur(val, 'hotSteam')"
                    >
                      <template #append>GJ/pcs</template>
                    </px-input>
                  </px-form-item>
                </px-col>
                <px-col :span="6">
                  <px-form-item label="单位产品大宗气能耗" prop="gas">
                    <px-input
                      v-model="detailParams.gas"
                      type="text"
                      maxlength="6"
                      :formatter="value => value.replace(/[^\d.]/g, '')"
                      :disabled="fromDisabled"
                      placeholder="最大值是100000"
                      clearable
                      @input="val => validateInput(val, 'gas')"
                      @blur="val => onInputBlur(val, 'gas')"
                    >
                      <template #append>GJ/pcs</template>
                    </px-input>
                  </px-form-item>
                </px-col>
              </px-row>
            </div>
            <px-row class="black">
              <px-col :span="14" :offset="8">
                <px-form-item label-width="180px" label="单位产品综合能耗基准" prop="standardValue" class="mg10">
                  <px-input
                    v-model="detailParams.standardValue"
                    type="text"
                    maxlength="6"
                    :formatter="value => value.replace(/[^\d.]/g, '')"
                    :disabled="fromDisabled"
                    placeholder="最大值是100000"
                    clearable
                    @input="val => validateInput(val, 'standardValue')"
                    @blur="val => onInputBlur(val, 'standardValue')"
                  >
                    <template #append>tce/pcs</template>
                  </px-input>
                </px-form-item>
              </px-col>
            </px-row>
          </ReCollapse>
          <ReCollapse class="mb-4" title="试算考核基准">
            <div class="top-select-btn">
              <px-form-item label="能源" label-width="60px" style="margin: 10px 0">
                <px-select v-model="detailParams.classCode" style="width: 200px" placeholder="请选择" @change="handleSelectChange">
                  <px-option v-for="item in energyList" :key="item.value" :label="item.label" :value="item.value" />
                </px-select>
              </px-form-item>
              <px-button type="primary" :disabled="fromDisabled" :loading="btnLoading" @click="handleTrialBalance">试算考核基准</px-button>
            </div>
            <div style="margin: 0 16px">
              <px-table :data="eqpCostData" border show-overflow-tooltip :header-cell-style="{ background: '#e7eefb', color: '#000' }">
                <px-table-column prop="className" label="考核项" fixed="left">
                  <template #default="scope">
                    <div :style="{ textAlign: scope.row.className === '厂务' ? 'center' : 'right' }">{{ scope.row.className }}</div>
                  </template>
                </px-table-column>
                <px-table-column prop="calcRatio" :label="tableColumnName" align="center">
                  <template #default="scope">
                    <div>{{ formatValue(scope.row.calcRatio) }}</div>
                  </template>
                </px-table-column>
                <px-table-column prop="realRatio" label="实际使用比列" align="center">
                  <template #default="scope">
                    <px-input-number
                      v-if="state.tableRowEditIndex === scope.$index && state.tableColumnEditIndex == scope.column.id"
                      ref="tableRowInputRef"
                      v-model="scope.row.realRatio"
                      :controls="false"
                      :max="100000"
                      :precision="10"
                      :value-on-clear="0"
                      @keyup.enter="
                        $event => {
                          $event.target.blur();
                        }
                      "
                      @blur="onInputTableBlur(scope)"
                    />
                    <div v-else class="eidt-row-p" style="cursor: pointer" @click="dbClickCell(scope)">{{ formatValue(scope.row.realRatio) }}</div>
                  </template>
                </px-table-column>
                <px-table-column prop="realCheckStandard" label="实际目标值(tce/pcs)" align="center" />
              </px-table>
            </div>
          </ReCollapse>
        </px-form>
      </div>
      <div v-if="isShowReTeleport">
        <ReTeleport>
          <div class="replace-bottle-add-teleport-btns">
            <px-button @click="cancelFn">取消</px-button>
            <px-button v-if="handleType !== 'VIEW'" type="primary" @click="confirmFn">保存</px-button>
          </div>
        </ReTeleport>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, computed, onMounted, nextTick, getCurrentInstance, toRaw } from "vue";
import { PxMessage, PxMessageBox } from "px-ui";
// import barTitle from "@/views/machine/components/barTitle/index.vue";
import lineCharts from "@/views/common/energy/components/lineCharts/index.vue";
import ReTeleport from "@/components/ReTeleport";
import ReCollapse from "@/components/ReCollapse";
import { ArrowLeft } from "@px-ui/icons-vue";
import { useRouterStoreHook } from "@/store/modules/router";
import {
  getViewPerformanceAPI,
  getListStandardAPI,
  getViewStandardAPI,
  updateStandardAPI,
  delStandardAPI,
  trialStandardAPI
} from "@/api/energy/performance";
import dayjs from "dayjs";

defineOptions({
  name: "ALL_ENERGY_PERFORMANCE_BENCHMARK"
});

const { proxy }: any = getCurrentInstance();

const showTable = ref(true);
const dialogVisible = ref(false);
const tableLoading = ref(false);
const fromDisabled = ref(false);
const isShowReTeleport = ref(false);
const linesOptions = ref<any>({});
const queryLineParams = ref<any>({});
const midKey = ref(Date.now());
// const eqpCostData = ref<any>([
//   {
//     className: "厂务",
//     classCode: "FACTORY_TASK",
//     calcRatio: "-",
//     realRatio: "-",
//     realCheckStandard: "-"
//   },
//   {
//     className: "机械科",
//     classCode: "MACHINE",
//     calcRatio: "-",
//     realRatio: "-",
//     realCheckStandard: "-"
//   },
//   {
//     className: "水科",
//     classCode: "WATER",
//     calcRatio: "-",
//     realRatio: "-",
//     realCheckStandard: "-"
//   },
//   {
//     className: "气化科",
//     classCode: "GAS",
//     calcRatio: "-",
//     realRatio: "-",
//     realCheckStandard: "-"
//   }
// ]);

const eqpCostDataCopy = [
  {
    className: "厂务",
    classCode: "FACTORY_TASK",
    calcRatio: "-",
    realRatio: "-",
    realCheckStandard: "-"
  },
  {
    className: "机械科",
    classCode: "MACHINE",
    calcRatio: "-",
    realRatio: "-",
    realCheckStandard: "-"
  },
  {
    className: "水科",
    classCode: "WATER",
    calcRatio: "-",
    realRatio: "-",
    realCheckStandard: "-"
  },
  {
    className: "气化科",
    classCode: "GAS",
    calcRatio: "-",
    realRatio: "-",
    realCheckStandard: "-"
  }
];

const handleType = ref("ADD");
const dateRange = ref([]);
const dateLineRange = ref([]);
const dateDetailRange = ref([]);
const tableRowInputRef: any = ref(null);
const detailParams = ref<any>({
  classCode: "1",
  detailList: [
    {
      trialList: [
        {
          className: "厂务",
          classCode: "FACTORY_TASK",
          calcRatio: "-",
          realRatio: "-",
          realCheckStandard: "-"
        },
        {
          className: "机械科",
          classCode: "MACHINE",
          calcRatio: "-",
          realRatio: "-",
          realCheckStandard: "-"
        },
        {
          className: "水科",
          classCode: "WATER",
          calcRatio: "-",
          realRatio: "-",
          realCheckStandard: "-"
        },
        {
          className: "气化科",
          classCode: "GAS",
          calcRatio: "-",
          realRatio: "-",
          realCheckStandard: "-"
        }
      ]
    }
  ]
});
const initialData = ref<any>(null);
const tableColumnName = ref<String>("电能耗推荐比例");
const currentEnergyIndex = ref(0);

const state = reactive({
  queryParams: {
    name: "",
    pageNum: 1,
    pageSize: 20,
    startTime: "",
    endTime: ""
  },
  tableRowEditIndex: undefined,
  tableColumnEditIndex: undefined,
  tableData: [],
  rules: {
    name: [{ required: true, message: "请输入名称", trigger: "blur" }],
    startTime: [{ required: true, message: "请选择时间", trigger: "blur" }]
    // standardValue: [{ required: true, message: "请输入单位产品综合能耗基准", trigger: "blur" }]
  },
  total: 0,
  chartLoading: false,
  detailLoading: false,
  addOrViewOrEdit: 1, // 1:add, 2:view,3:edit
  btnLoading: false
});
const { queryParams, tableData, rules, total, chartLoading, detailLoading, btnLoading } = toRefs(state);

const eqpCostData = computed({
  get() {
    if (detailParams.value.detailList && detailParams.value.detailList.length > 0) {
      return detailParams.value.detailList[currentEnergyIndex.value]?.trialList || [];
    }
    return [];
  },
  set(newValue) {
    if (detailParams.value.detailList && detailParams.value.detailList.length > 0) {
      // 直接替换整个 data 数组
      detailParams.value.detailList[currentEnergyIndex.value].trialList = newValue;
    }
  }
});

const energyList = [
  {
    value: "1",
    label: "电",
    flag: "electricity"
  },
  {
    value: "2",
    label: "总能耗折标煤",
    flag: "standardValue"
  },
  {
    value: "3",
    label: "自来水",
    flag: "water"
  },
  {
    value: "4",
    label: "再生水",
    flag: "reclaim"
  },
  {
    value: "5",
    label: "天然气",
    flag: "ng"
  },
  // {
  //   value: "6",
  //   label: "蒸汽",
  //   flag: "steam"
  // },
  // {
  //   value: "7",
  //   label: "热水",
  //   flag: "hotwater"
  // },
  {
    value: "8",
    label: "大宗气",
    flag: "gas"
  },
  {
    value: "9",
    label: "蒸汽/热水",
    flag: "hotSteam"
  }
];

// 处理值
const formatValue = val => {
  if (val) return val;
  if (val === "0") return 0;
  return "-";
};

// 重置数据
const resetData = () => {
  currentEnergyIndex.value = 0;
  tableColumnName.value = "电能耗推荐比例";
  initialData.value = null;
  dateDetailRange.value = [];
};

// 双击可编辑的单元格
const dbClickCell = (scope: any) => {
  console.log(scope);
  if (fromDisabled.value) {
    return;
  }
  // 找到单个格子独有的属性 - 这里是用所在行跟列id区别显示
  state.tableRowEditIndex = scope.$index;
  state.tableColumnEditIndex = scope.column.id;
  nextTick(() => {
    // 获取焦点
    tableRowInputRef.value.focus();
  });
};

// 表单输入框输入值继续计算
const onInputBlur = (val, args) => {
  console.log("取消焦点", val);
  let currentNum = detailParams.value[args];
  setCurrentEnergy();
  detailParams.value.detailList[currentEnergyIndex.value]?.trialList?.forEach(i => {
    if (currentNum && i.realRatio !== "-") {
      i.realCheckStandard = i.realRatio * currentNum;
    } else {
      i.realCheckStandard = "-";
    }
  });
};

// 表格中input取消焦点,select变化
const onInputTableBlur = (scope: any) => {
  console.log("取消焦点", scope);
  state.tableRowEditIndex = undefined;
  state.tableColumnEditIndex = undefined;
  let obj = energyList.find(i => i?.value == detailParams.value.classCode);
  let currentNum = detailParams.value[obj?.flag];
  if (currentNum && scope.row.realRatio !== "-") {
    scope.row.realCheckStandard = scope.row.realRatio * currentNum;
  }
};

// 列表
const getList = async () => {
  try {
    tableLoading.value = true;
    const { pageNum, pageSize, name } = state.queryParams;
    const params = {
      pageNum,
      pageSize,
      name,
      startTime: "",
      endTime: ""
    };
    const res: any = await getListStandardAPI(params);
    if (res?.data?.length) {
      tableData.value = res?.data || [];
      total.value = res?.total;
    } else {
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.log(error);
  } finally {
    tableLoading.value = false;
  }
};

//  重置按钮操作
const resetQuery = () => {
  dateRange.value = [];
  proxy.$refs["queryRef"].resetFields();
  getList();
};

// 时间改变
const changeTime = val => {
  if (val) {
    let startTime = dayjs(val[0]).format("YYYY-MM") + "-01 00:00:00";
    let endTime = dayjs(val[1]).endOf("month").format("YYYY-MM-DD") + " 23:59:59";
    detailParams.value.startTime = startTime;
    detailParams.value.endTime = endTime;
  } else {
    detailParams.value.startTime = null;
    detailParams.value.endTime = null;
  }
};

// 历史数据分析
const historyAnsys = () => {
  let sDate = dayjs().subtract(12, "month").format("YYYY-MM") + "-01 00:00:00";
  let eDate = dayjs().endOf("month").format("YYYY-MM-DD") + " 23:59:59";
  dialogVisible.value = true;
  dateLineRange.value = [sDate, eDate];
  nextTick(() => {
    getLineData();
  });
};

// 历史数据分析---获取折线图数据
const getLineData = async () => {
  try {
    state.chartLoading = true;
    let startDate = dayjs(dateLineRange.value[0]).format("YYYY-MM") + "-01 00:00:00";
    let endDate = dayjs(dateLineRange.value[1]).endOf("month").format("YYYY-MM-DD") + " 23:59:59";
    const params = {
      dimension: "MONTH",
      startDate: startDate,
      endDate: endDate,
      factory: "",
      sysId: ""
    };
    const res: any = await getViewPerformanceAPI(params);
    const trend: any = res?.trend || {};
    linesOptions.value = labelLayoutFn(trend);
    midKey.value = Date.now();
  } catch (error) {
    console.log(error);
  } finally {
    state.chartLoading = false;
  }
};

//  历史数据分析---获取折线图的options
const labelLayoutFn = (data: any) => {
  const options: CommonEcharts.CommonEchartsOption = {
    title: {
      text: data.yaxis[0].name,
      left: "center"
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross"
      }
    },
    grid: {
      left: 0,
      right: 0,
      top: "10%",
      bottom: "10px",
      containLabel: true
    },
    xAxis: {
      type: "category",
      data: data.xaxis || []
    },
    yAxis: {
      type: "value",
      name: "单位产品能耗：tce/pcs",
      nameLocation: "end",
      nameTextStyle: {
        align: "left",
        padding: [0, 0, 0, 0]
      },
      nameGap: 20,
      axisLine: {
        show: true
      }
    },
    series: [
      {
        name: "",
        type: "line",
        labelLine: {
          length: 15,
          length2: 0,
          maxSurfaceAngle: 80
        },
        data: data.yaxis[0].value
      }
    ]
  };
  return options;
};

// 新增的时候,给detailParams
const setDetailParamsData = () => {
  detailParams.value = {
    classCode: "1",
    detailList: []
  };
  let detailList = [];
  energyList?.forEach(i => {
    detailList.push({
      energyType: Number(i.value),
      energyName: i.label,
      standardValue: "",
      trialList: JSON.parse(JSON.stringify(eqpCostDataCopy))
    });
  });
  detailParams.value.detailList = detailList;
};

// 新增、查看、编辑
const handleFn = async (row: any, type: string) => {
  try {
    state.detailLoading = true;
    handleType.value = type;
    showTable.value = false;
    // 新增
    if (type === "ADD") {
      resetData();
      fromDisabled.value = false;
      isShowReTeleport.value = true;
      initialData.value = toRaw({ ...detailParams.value });
      state.addOrViewOrEdit = 1;
      setDetailParamsData();
      setCurrentEnergy();
    }
    // 查看、编辑
    if (["VIEW", "EDIT"].includes(type)) {
      const res: any = await getViewStandardAPI({ id: row.id });
      let data = JSON.parse(JSON.stringify(res));
      detailParams.value = data;
      detailParams.value.classCode = "1";
      res?.detailList?.forEach(i => {
        energyList?.forEach(j => {
          if (i.energyType === Number(j.value)) {
            detailParams.value[j.flag] = Number(i.standardValue);
          }
        });
      });
      setCurrentEnergy();
      if (res.startTime && res.endTime) {
        dateDetailRange.value = [res.startTime, res.endTime];
      }
      initialData.value = toRaw({ ...detailParams.value });
      // 查看
      if (type === "VIEW") {
        fromDisabled.value = true;
        state.addOrViewOrEdit = 2;
      }
      // 编辑
      if (type === "EDIT") {
        fromDisabled.value = false;
        isShowReTeleport.value = true;
        state.addOrViewOrEdit = 3;
      }
    }
  } catch (error) {
    console.log(error);
  } finally {
    state.detailLoading = false;
  }
};

// 删除
const handleDelete = (row: any) => {
  PxMessageBox.confirm(`是否确认删除名称为${row.name}的数据项？`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    confirmButtonClass: "px-button--danger",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await delStandardAPI({ id: row.id });
      PxMessage.success("删除成功");
      getList();
    })
    .catch(error => {
      console.log(error);
    });
};

// 保存
const confirmFn = () => {
  console.log(" detailParams.value.detailList", detailParams.value.detailList);
  detailParams.value.detailList?.forEach(i => {
    i?.trialList?.forEach(j => {
      j.calcRatio = j.calcRatio === "-" ? "" : j.calcRatio;
      j.realRatio = j.realRatio === "-" ? "" : j.realRatio;
      j.realCheckStandard = j.realCheckStandard === "-" ? "" : j.realCheckStandard;
    });
    energyList?.forEach(k => {
      if (Number(k.value) == i.energyType) {
        i.standardValue = detailParams.value[k.flag];
      }
    });
  });
  // 拿一些参数
  let { id, name, startTime, endTime, standardValue, detailList = [] } = detailParams.value;
  const params = {
    id: id ?? "",
    name,
    startTime,
    standardValue: Number(standardValue),
    endTime,
    detailList: detailList
  };
  proxy.$refs["detailRef"].validate(valid => {
    if (!valid) return;
    PxMessageBox.confirm(`请一定保证数据的准确性，保存后相关计算数据生成无法修正，继续保存吗？`, "温馨提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      draggable: true
    })
      .then(async () => {
        const res = await updateStandardAPI(params);
        if (res) {
          PxMessage.success("保存成功");
          showTable.value = true;
          const routeStore = useRouterStoreHook();
          routeStore.SET_BOTTOM_FOOTER_HEIGHT(0);
          isShowReTeleport.value = false;
          getList();
        }
      })
      .catch(() => {});
  });
};

// 设置能源表格的数据
const setCurrentEnergy = () => {
  // 找索引
  currentEnergyIndex.value = detailParams.value.detailList?.findIndex(i => Number(i?.energyType) === Number(detailParams.value.classCode));
};

// 检查表单是否被修改
const isFormChanged = () => {
  // 深度比较当前数据与初始数据
  return JSON.stringify(detailParams.value) !== JSON.stringify(initialData.value);
};

// 返回、取消
const cancelFn = () => {
  // 查看
  if (handleType.value === "VIEW") {
    isShowReTeleport.value = false;
    const routeStore = useRouterStoreHook();
    routeStore.SET_BOTTOM_FOOTER_HEIGHT(0);
    showTable.value = true;
  }
  // 数据是否改变
  if (isFormChanged()) {
    PxMessageBox.confirm(`数据未保存，是否退出？`, "温馨提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      draggable: true
    })
      .then(() => {
        isShowReTeleport.value = false;
        const routeStore = useRouterStoreHook();
        routeStore.SET_BOTTOM_FOOTER_HEIGHT(0);
        showTable.value = true;
      })
      .catch(() => {});
  } else {
    isShowReTeleport.value = false;
    const routeStore = useRouterStoreHook();
    routeStore.SET_BOTTOM_FOOTER_HEIGHT(0);
    showTable.value = true;
  }
};

// 能源下拉框数据的变化
const handleSelectChange = val => {
  // 改列名
  let obj = energyList?.find(i => i?.value === val);
  tableColumnName.value = obj?.label + "能耗推荐比例";
  // 找索引
  setCurrentEnergy();
  // 计算表格的值
  let currentNum = detailParams.value[obj?.flag];
  detailParams.value.detailList[currentEnergyIndex.value]?.trialList?.forEach(i => {
    if (currentNum && i.realRatio !== "-") {
      i.realCheckStandard = i.realRatio * currentNum;
    } else {
      i.realCheckStandard = "-";
    }
  });
};

// 试算考核基准
const handleTrialBalance = async () => {
  try {
    state.btnLoading = true;
    let { startTime, endTime } = detailParams.value;
    let standardValue = "";
    energyList?.forEach(i => {
      if (i.value === detailParams.value.classCode) {
        standardValue = detailParams.value[i.flag];
      }
    });
    const parame = {
      startTime,
      endTime,
      energyType: Number(detailParams.value.classCode),
      standardValue
    };
    if (startTime && endTime) {
      const res: any = await trialStandardAPI(parame);
      if (res?.length) {
        let data = res?.filter(i => i.energyType === Number(detailParams.value.classCode));
        data?.forEach(i => {
          eqpCostData.value?.forEach(j => {
            if (i?.classCode === j.classCode) {
              j.calcRatio = i.calcRatio;
            }
          });
        });
      }
    }
  } catch (error) {
    console.log(error);
  } finally {
    state.btnLoading = false;
  }
};

onMounted(() => {
  getList();
});

// 输入框的校验
const validateInput = (val, args) => {
  let num = val.replace(/\D/g, "");
  if (num && Number(num) > 100000) {
    num = 100000;
  }
  detailParams.value[args] = num;
};
</script>

<style lang="scss" scoped>
.hidden {
  display: none;
}

.tabs {
  /*
    * tab样式
    */
  .tabSwitch {
    padding: 4px;
    margin-bottom: 16px;
    background-color: #f4f4f4;
    border-radius: 4px;

    :deep(.px-radio-button__inner) {
      background-color: #f4f4f4;
      border: none;
    }

    :deep(.is-active) {
      border: none;

      .px-radio-button__inner {
        background-color: var(--px-color-primary);
        border-radius: 4px;
      }
    }
  }
}

.replace-bottle-add-teleport-btns {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
  height: 100%;
  padding: 16px;
}

.add-edit-content {
  border-radius: 8px;
}

.add-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-top: 16px;

  .base-info-form {
    box-sizing: border-box;

    .form-item-con {
      padding: 16px;

      .year-month {
        display: flex;
        height: 72px;

        :deep(.px-input) {
          display: flex !important;
          flex-flow: column nowrap !important;
          height: 36px !important;
        }

        :deep(.px-input-group__prepend) {
          border-right: 1px !important;
          border-radius: 4px !important;
        }

        :deep(.px-form-item) {
          margin: 0;
        }

        :deep(.px-form-item__error) {
          position: absolute;
          top: 100%;
          left: 0;
          padding-top: 2px;
          font-size: 12px;
          line-height: 1;
          color: var(--px-color-danger);
        }
      }
    }

    .black {
      border-top: 1px solid #dfdfdf;
      border-bottom: 1px solid #dfdfdf;

      .mg10 {
        margin: 18px;
      }
    }

    .px-form-item {
      .px-select {
        width: 100%;
      }

      .px-input {
        width: 100%;
      }

      :deep(.px-date-editor) {
        width: 100%;
      }
    }
  }
}

:deep(.px-input-number) {
  width: 100%;
}

:deep(.px-input__inner) {
  text-align: left;
}

.month-text {
  width: 100%;
  text-align: center;
  border: 1px solid #ccc;
  border-bottom: none;
  border-radius: 4px;
}

.chart_item {
  height: 500px;
}

.top-select-btn {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 16px;
}
</style>
